package com.yupin.mail;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.swing.JOptionPane;

public class MailUtil {
	
	public static void main(String[] args) {
		fetchMail("hzyh64160", "Ytxsgmay0707");		
	}
	
	public static void fetchMail(String username, String password){
		try {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FFACTORY = "javax.net.ssl.SSLSocketFactory";

			Properties props = System.getProperties();
			props.setProperty("mail.pop3.socketFactory.class", SSL_FFACTORY);
			props.setProperty("mail.pop3.socketFactory.fallback", "false");
			props.setProperty("mail.pop3.port", "995");
			props.setProperty("mail.pop3.socketFactory.port", "995");

			Session session = Session.getDefaultInstance(props, null);

			URLName urln = new URLName("pop3", "pop.gmail.com", 995, null,
					username, password);

			Store store = session.getStore(urln);
			Folder inbox = null;
			store.connect();
			inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			FetchProfile profile = new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			Message[] messages = inbox.getMessages(1, 5);
			inbox.fetch(messages, profile);
			System.out.println("Mails in Inbox: " + messages.length);
			for(int i = 0; i < 5; i++){
				String from = decodeText(messages[i].getFrom()[0].toString());
				InternetAddress ia = new InternetAddress(from);
				System.out.println("FROM: " + ia.getPersonal() + "(" + ia.getAddress() + ")");
				System.out.println("TITLE: " + messages[i].getSubject());
				System.out.println("SIZE: " + messages[i].getSize());
				System.out.println("DATE: " + messages[i].getSentDate()); 
			}
			
			inbox.close(false);
			store.close();
			
			
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected static String decodeText(String text)

			throws UnsupportedEncodingException {
		if (text == null)
			return null;
		if (text.startsWith("=?GB") || text.startsWith("=?gb"))
			text = MimeUtility.decodeText(text);
		else
			text = new String(text.getBytes("ISO8859_1"));
		return text;
}
	
	public static void sendEmail(final String username, final String password, String receiver, String subject, String content){
		try {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

			Properties props = System.getProperties();
			props.setProperty("mail.smtp.host", "smtp.gmail.com");
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.port", "465");
			props.setProperty("mail.smtp.socketFactory.port", "465");
			props.put("mail.smtp.auth", "true");


			Session session = Session.getDefaultInstance(props,
					new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username,
									password);
						}

					});

			Message msg = new MimeMessage(session);

			msg.setFrom(new InternetAddress(username + "@gmail.com"));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver,false));
			msg.setSubject(subject);
			msg.setText(content);
			msg.setSentDate(new Date());
			Transport.send(msg);
			
			
			JOptionPane.showMessageDialog(null, "Mail sent!");
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
}
